import * as THREE from "three";
import { OrbitControls } from "three/addons/controls/OrbitControls.js";
import { GUI } from "three/addons/libs/lil-gui.module.min.js";
import { EffectComposer } from "three/addons/postprocessing/EffectComposer.js";
import { RenderPass } from "three/addons/postprocessing/RenderPass.js";
import { OutlinePass } from "three/addons/postprocessing/OutlinePass.js";
import { UnrealBloomPass } from "three/addons/postprocessing/UnrealBloomPass.js";

import group from "./mesh.js";

const scene = new THREE.Scene();
scene.add(group);

// 添加光源
const directionalLight = new THREE.DirectionalLight(0xffffff, 1);
directionalLight.position.set(300, 300, 300);
scene.add(directionalLight);
const ambientLight = new THREE.AmbientLight(0x404040, 1);
scene.add(ambientLight);

// 创建相机
const width = window.innerWidth;
const height = window.innerHeight;
const camera = new THREE.PerspectiveCamera(60, width / height, 1, 10000);
camera.position.set(0, 500, 500);
camera.lookAt(0, 0, 0);

// 创建渲染器
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
renderer.domElement.addEventListener("click", function (event) {
	const mouse = new THREE.Vector2();
	mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
	mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;

	const raycaster = new THREE.Raycaster();
	raycaster.setFromCamera(mouse, camera);

	const intersects = raycaster.intersectObjects(group.children);
	if (intersects.length > 0) {
		outlinePass.selectedObjects = [intersects[0].object];

		if (!composer.passes.includes(bloomPass)) {
			composer.addPass(bloomPass);
		}
	} else {
		outlinePass.selectedObjects = [];
		composer.removePass(bloomPass);
	}
	// intersects.forEach((intersect) => {
	// 	intersect.object.material.color.set("blue");
	// });
});

// 创建后期处理
const composer = new EffectComposer(renderer);
// 添加渲染通道
const renderPass = new RenderPass(scene, camera);
composer.addPass(renderPass);
// 添加轮廓通道
const v2 = new THREE.Vector2(width, height);
const outlinePass = new OutlinePass(v2, scene, camera);
outlinePass.visibleEdgeColor.set("orange");
outlinePass.edgeStrength = 10.0; // 边缘强度
outlinePass.edgeThickness = 10.0; // 边缘厚度
outlinePass.pulsePeriod = 1; // 闪烁周期
composer.addPass(outlinePass);

// 添加辉光通道
const bloomPass = new UnrealBloomPass(v2, 1.5, 0.4, 0.85);
bloomPass.threshold = 0.5;
bloomPass.strength = 0.8;
composer.addPass(bloomPass);

// 渲染
function render() {
	composer.render();
	requestAnimationFrame(render);
	// renderer.render(scene, camera);
}
render();

//添加坐标轴辅助器
const axesHelper = new THREE.AxesHelper(200);
scene.add(axesHelper);

//轨道控制器
const controls = new OrbitControls(camera, renderer.domElement);
controls.addEventListener("change", function () {
	renderer.render(scene, camera);
});

//调试工具
const gui = new GUI();
